package com.yunshan.system.test;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @Author: wss
 * @DateTime: 2025/2/25 11:17
 **/
public class WeChatMessageSender {
    // 发送微信公众号模板消息的URL
    private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    /**
     * 发送微信公众号模板消息
     *
     * @param accessToken  Access Token
     * @param touser       接收消息的用户 OpenID
     * @param templateId   模板ID
     * @param data         模板数据，JSON 格式
     * @return 响应结果
     */
    public static String sendTemplateMessage(String accessToken, String touser, String templateId, String data) {
        String url = API_URL + accessToken;
        String payload = buildRequestPayload(touser, templateId, data);

        try {
            // 创建URL对象
            URL urlObj = new URL(url);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");

            // 发送POST请求
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = payload.getBytes(StandardCharsets.UTF_8);
                outputStream.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return "消息发送成功";
            } else {
                return "消息发送失败，响应码：" + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "发送消息时出错：" + e.getMessage();
        }
    }

    /**
     * 构建请求的JSON负载
     *
     * @param touser     接收消息的用户 OpenID
     * @param templateId 模板ID
     * @param data       模板数据
     * @return 请求体的 JSON 字符串
     */
    private static String buildRequestPayload(String touser, String templateId, String data) {
        return "{"
                + "\"touser\": \"" + touser + "\","
                + "\"template_id\": \"" + templateId + "\","
                + "\"data\": " + data
                + "}";
    }

    public static void main(String[] args) {
        // 示例使用
        String accessToken = "YOUR_ACCESS_TOKEN";  // 获取的 access_token
        String touser = "USER_OPENID";  // 目标用户的 OpenID
        String templateId = "TEMPLATE_ID";  // 模板消息的模板 ID
        String data = "{\"first\": {\"value\": \"恭喜您，购买成功！\"}, \"keyword1\": {\"value\": \"商品名称\"}, \"keyword2\": {\"value\": \"订单编号\"}, \"remark\": {\"value\": \"感谢您的购买！\"}}";  // 模板数据（实际数据根据你的模板定义来填写）

        String response = sendTemplateMessage(accessToken, touser, templateId, data);
        System.out.println(response);
    }
}
